package cn.truistic.enmicromsg.common.util;

import android.text.TextUtils;
import android.util.Log;
import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;
import org.litepal.crud.DataSupport;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.truistic.enmicromsg.Message;
import cn.truistic.enmicromsg.bean.Contact;
import cn.truistic.enmicromsg.bean.WeChatFile;

/**
 * Created by admin on 2018/6/11.
 */

public class CursorUtils {

    private static String WX_FILE_PATH = "/storage/emulated/0/Tencent/micromsg/";

    public static int openMessageTable( SQLiteDatabase db , String uinStr ) {
        Cursor cursor = null;
        Cursor imgInfoCu = null;
        try {
            // 一般公众号原始ID开头都是gh_
            cursor = db.rawQuery("select * from message where talker not like 'gh_%' and msgid > ? ", new String[]{getLastMsgId(db)});// new String[]{ getLastMsgId(db)}   new String[]{"0"}
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    String msgSvrId = cursor.getString(cursor.getColumnIndex("msgSvrId"));
                    String type = cursor.getString(cursor.getColumnIndex("type"));
                    String isSend = cursor.getString(cursor.getColumnIndex("isSend"));
                    Long createTime = cursor.getLong(cursor.getColumnIndex("createTime"));
                    String talker = cursor.getString(cursor.getColumnIndex("talker"));
                    String content = cursor.getString(cursor.getColumnIndex("content"));
                    String status = cursor.getString(cursor.getColumnIndex("status"));
                    if (TextUtils.isEmpty(content)) content = "";
                    String imgPath = cursor.getString(cursor.getColumnIndex("imgPath"));
                    if (TextUtils.isEmpty(imgPath)) imgPath = "";
                    // 根据“msgSvrId”来判断聊天记录唯一性
                    if (TextUtils.isEmpty(msgSvrId)) {
                        Log.e("TAG", "该次记录 msgSvrId 为空，跳过");
                        continue;
                    }
                    if (TextUtils.isEmpty(talker)) {
                        talker = "";
                    }
                    Log.e("TAG", msgSvrId + "------>" + type + "-------->" + content);

                    List<Message> list = DataSupport.where("msgSvrId = ?", msgSvrId).find(Message.class);
                    if (list.isEmpty()) {
                        Message message = new Message();
                        message.setMsgSvrId(msgSvrId);
                        message.setType(type);
                        message.setTalker(talker);
                        // 内容不做处理，直接上传
                    /*message.content = when (message.type) {
                        "1" -> content
                        "3" -> "[图片]"
                        "34" -> "[语音]"
                        "47" -> "[表情]"
                        "50" -> "[语音/视频通话]"
                        "43" -> "[小视频]"
                        "49" -> "[分享]"
                        "48" -> content          // 位置信息
                        "10000" -> content       // 系统提示信息
                        else -> content          // 其他信息，包含红包、转账等
                    }*/
                        message.setStatus(isSend);
                        message.setCreateTime(TimeUtils.timeFormat(createTime, TimeUtils.TIME_STYLE));
                        // 保存图片、语音、小视频文件信息
                        if (type.equals("3") || type.equals("34") || type.equals("43")) {
                            WeChatFile weChatFile = new WeChatFile();
                            weChatFile.setMsgSvrId(msgSvrId);
                            weChatFile.setType(type);
                            weChatFile.setDate(new Date().getTime());
                            switch (type) {
                                case "3":
                                    // 图片文件需要根据msgSvrId在ImgInfo2表中查找
                                    imgInfoCu = db.rawQuery("select bigImgPath from ImgInfo2 where msgSvrId = ? ", new String[]{msgSvrId});
                                    if (imgInfoCu.getCount() > 0) {
                                        while (imgInfoCu.moveToNext()) {
                                            String bigImgPath = imgInfoCu.getString(imgInfoCu.getColumnIndex("bigImgPath"));
                                            weChatFile.setName(bigImgPath);
                                        }
                                    }
                                    imgInfoCu.close();
                                    weChatFile.setPath(WX_FILE_PATH + MD5Util.INSTANCE.md5("mm" + uinStr) + "/image2/" + weChatFile.getName().substring(0, 2) + "/" + weChatFile.getName().substring(2, 4) + "/" + weChatFile.getName());
                                    // 接收的图片在ImgInfo2表中会有两种bigImgPath，一种是原图，一种是缓存图，缓存图的格式是文件.temp.jpg
                                    // 如果有原图，则上传原图，否则上传缓存图
                                    // 过滤一些不是jpg的文件
                                    if (weChatFile.getPath().contains(".temp")) {
                                        String originalImgPath = weChatFile.getPath().replace(".temp", "");
                                        if (new File(originalImgPath).exists()) {
                                            weChatFile.setName(weChatFile.getName().replace(".temp", ""));
                                            weChatFile.setPath(originalImgPath);
                                            try {
                                                File file = new File(weChatFile.getPath());
                                                String encodeBase64Str = Base64Encoder.encodeBase64File(file);
                                                message.setContent(encodeBase64Str);
                                                Log.e("TAG ", "------------》缓存图这里是哈哈哈哈");
                                            } catch ( Exception e ) {
                                                message.setContent("图片获取失败..");
                                            }
                                        }
                                    }else{
                                        message.setContent("[图片未获取]");
                                    }
                                    if ( weChatFile.getName().endsWith(".jpg")) {
                                        try {
                                            File file = new File(weChatFile.getPath());
                                            String encodeBase64Str = Base64Encoder.encodeBase64File(file);
                                            message.setContent(encodeBase64Str);
                                            Log.e("TAG ", "------------》缓存原图这里是哈哈哈哈");
                                        } catch ( Exception e ) {
                                            message.setContent("图片获取失败..");
                                        }
                                    }else{
                                        message.setContent("[图片未获取]");
                                    }
                                    Log.e("TAG", weChatFile.getPath());
                                    //设置单聊和群聊的type
                                    weChatFile.save();
                                    break;
                                case "34":
                                    //音频
                                    weChatFile.setName("msg_" + imgPath + ".amr");
                                    String nameEnc = MD5Util.INSTANCE.md5(imgPath);
                                    weChatFile.setPath(WX_FILE_PATH + MD5Util.INSTANCE.md5("mm" + uinStr) + "/voice2/" + nameEnc.substring(0, 2) + "/" + nameEnc.substring(2, 4) + "/" + weChatFile.getName());//图片地址
                                    try {
                                        File file = new File(weChatFile.getPath());
                                        String encodeBase64Str = Base64Encoder.encodeBase64File(file);
                                        message.setContent(encodeBase64Str);
                                    } catch (Exception e) {
                                        message.setContent("音频获取失败..");
                                    }
                                    weChatFile.save();
                                    break;
                                case "43":
                                    //视频
                                    weChatFile.setName(imgPath + ".jpg");
                                    weChatFile.setPath(WX_FILE_PATH + MD5Util.INSTANCE.md5("mm" + uinStr) + "/video/" + weChatFile.getName()); //视频地址
                                    try {
                                        File file = new File(weChatFile.getPath());
                                        String encodeBase64Str = Base64Encoder.encodeBase64File(file);
                                        message.setContent(encodeBase64Str);
                                    } catch (Exception e) {
                                        message.setContent("视频获取失败..");
                                    }
                                    weChatFile.save();
                                    break;
                            }
                            if (talker.endsWith("@chatroom")) {
                                message.setIsChatRoot(1);
                                message.setChatRoot(talker);
                                try {
                                    String[] arr = content.split(":");
                                    message.setTalker( arr[0] );
                                } catch ( Exception e ) {
                                    message.setTalker(talker);
                                }
                            } else {
                                message.setIsChatRoot(0);
                            }
                            message.save();
                        } else if (type.equals("1")) {
                            //文本内容
                            if (talker.endsWith("@chatroom")) {
                                //群聊
                                message.setIsChatRoot(1);
                                message.setChatRoot(talker);
                                if (content.contains("??")) {
                                    message.setContent(stringToUnicode(content.replace("??" ,"[未知表情]")));
                                } else {
                                    try {
                                        String[] str = content.split(":");
                                        message.setTalker(str[0]);
                                        message.setContent(stringToUnicode(str[1]));
                                    } catch (Exception e) {
                                        message.setContent(content);
                                    }
                                }
                            } else {
                                message.setIsChatRoot(0);
                                if ( content.contains("??") ) {
                                    message.setContent(stringToUnicode(content.replace("??" ,"[未知表情]")));
                                } else {
                                    message.setContent(stringToUnicode(content));
                                }
                            }
                            message.save();
                        } else if (type.equals("50")) {
                            message.setContent("拨打音视频");
                            message.save();
                        } else if (type.equals("47")) {
                            message.setContent("自定义图片");
                            if (talker.endsWith("@chatroom")) {
                                //群聊
                                message.setIsChatRoot(1);
                                message.setChatRoot(talker);
                                try {
                                    String[] str = content.split(":");
                                    message.setTalker(str[0]);
                                    message.setContent(str[1] );
                                } catch ( Exception e ) {
                                    message.setContent( content );
                                }
                            } else {
                                message.setIsChatRoot(0);
                            }
                            message.save();
                        }
                    }
                }
            }
            return 1;
        } catch (Exception e) {
            return 0;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (imgInfoCu != null) {
                imgInfoCu.close();
            }
        }
    }

    // 获取最后一条消息ID
    private static String getLastMsgId(SQLiteDatabase db) {
        Cursor msgCu = null;
        try {
            // 查询本地数据库中的最后一条
            String lastMsgId = "0";
            cn.truistic.enmicromsg.Message last = DataSupport.findLast(cn.truistic.enmicromsg.Message.class);
            if (last != null) {
                Log.e("TAG", "本地数据库中存在最后一条记录，msgSvrid:" + last.getMsgSvrId());
                msgCu = db.rawQuery(" select * from message where msgsvrid = ? ", new String[]{last.getMsgSvrId()});
                if (msgCu.getCount() > 0) {
                    while (msgCu.moveToNext()) {
                        lastMsgId = msgCu.getString(msgCu.getColumnIndex("msgId"));
                        Log.e("TAG", "微信数据库中存在 msgSvrid 为：" + last.getMsgSvrId() + " 的记录，msgid 为：" + lastMsgId);
                    }
                }
            }
            return lastMsgId;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (msgCu != null) {
                msgCu.close();
            }
        }
        return "";
    }


    // 打开联系人表
    public static int openContactTable(SQLiteDatabase db) {
        // verifyFlag!=0：公众号等类型 type=33：微信功能 type=2：未知 type=4：非好友
        // 一般公众号原始ID开头都是gh_
        // 群ID的结尾是@chatroom
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("select * from rcontact where " +
                    "type != ? and " +
                    "type != ? and " +
                    "type != ? and " +
                    "verifyFlag = ? and " +
                    "username not like 'gh_%' and " +
                    "username not like '%@chatroom' ", new String[]{"2", "33", "4", "0"});
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    String username = cursor.getString(cursor.getColumnIndex("username")); //微信号
                    String nickname = stringToUnicode(cursor.getString(cursor.getColumnIndex("nickname"))); //昵称
                    String type = cursor.getString(cursor.getColumnIndex("type"));
                    String conRemark = stringToUnicode(cursor.getString(cursor.getColumnIndex("conRemark"))); //标记
                    Log.e("TAG", username + "----->" + nickname + "------>" + type);
                    if (TextUtils.isEmpty(username)) {
                        nickname = "";
                    }
                    if (TextUtils.isEmpty(nickname)) {
                        nickname = "";
                    }
                    if (TextUtils.isEmpty(type)) {
                        type = "";
                    }
                    if (TextUtils.isEmpty(conRemark)) {
                        conRemark = "";
                    }
                    // 避免保存重复数据
                    List<Contact> listContact = DataSupport.where("Alias = ?", username).find(Contact.class);
                    if (listContact.isEmpty()) {
                        Contact contact = new Contact();
                        contact.setAlias(username);
                        contact.setNickName(nickname);
                        contact.setType(type);
                        contact.setRemarkName(conRemark);
                        contact.setWxid(username);
                        contact.save();
                    }
                }
            }
            return 1;
        } catch (Exception e) {
            return 0;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    //字符串转换unicode
    public static String stringToUnicode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++)
        {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>>8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }

    // 打开用户信息表
    public static int openUserInfoTable(SQLiteDatabase db) {
        List<String> values = null;
        Cursor cursor = null;
        // 这个数组是保存用户信息，第一次拿到的是账号，第二次是昵称
        try {
            values = new ArrayList<String>();
            // 用户信息表
             cursor = db.rawQuery("select value from userinfo where id = ? or id = ?", new String[]{"2", "42"});// "4"
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    String value = cursor.getString(cursor.getColumnIndex("value"));
                    values.add(value);
                }
            }
            if (values.size() > 1) {
                PreferenceHelper.commitString("userName", values.get(1));
                return 1;
            }else if (values.size() ==1 ){
                PreferenceHelper.commitString("userName", values.get(0));
                return 1;
            }else if (values.size() == 0){
                return 0;
            }
            PreferenceHelper.commitBoolean("isUpload", true);
            return 1;
        } catch (Exception e) {
            if (values.size() > 1) {
                PreferenceHelper.commitString("userName", values.get(1));
                return 1;
            }else if (values.size() ==1 ){
                PreferenceHelper.commitString("userName", values.get(0));
                return 1;
            }else if (values.size() == 0){
                return 0;
            }
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return -1;
    }
}
